package cn.udrm.elasticsearch.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

@Slf4j
public class Md5CaculateUtil {

    private static char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String getMD5(File file){

        String str = "";
        try {
            str = getHash(file, "MD5");
        } catch (Exception e) {
            log.error("文件加密失败！",e);
        }
        return str;
    }

    private static String getHash(File file, String hashType)
            throws Exception {
        InputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance(hashType);
        for (int numRead = 0; (numRead = fis.read(buffer)) > 0;)
            md5.update(buffer, 0, numRead);

        md5.update(file.getName().getBytes());//增加此处防止不同路径下的相同文件被过滤掉
        fis.close();
        return toHexString(md5.digest());
    }

    private static String toHexString(byte b[]) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(hexChar[(b[i] & 240) >>> 4]);
            sb.append(hexChar[b[i] & 15]);
        }

        return sb.toString();
    }
}
